﻿<%@ WebHandler Language="C#" Class="imgup" %>


using System;
using System.Web;
using System.Text;
using System.IO;
using System.Drawing;

public class imgup : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.ContentEncoding = Encoding.UTF8;
        if (context.Request["REQUEST_METHOD"] == "OPTIONS")
        {
            context.Response.End();
        }
        SaveFile();
    }

    /// <summary>
    /// 文件保存操作
    /// </summary>
    /// <param name="basePath"></param>
    private void SaveFile(string basePath = "/upload/")
    {
        string _datePath = DateTime.Now.ToString("yyyyMMdd") + "/";
        basePath += _datePath;

        string serverPath = "~" + basePath;
        var name = string.Empty;
        serverPath = (serverPath.IndexOf("~") > -1) ? System.Web.HttpContext.Current.Server.MapPath(serverPath) :
        serverPath;
        HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

        if (!Directory.Exists(serverPath))
            Directory.CreateDirectory(serverPath);


        //var suffix = files[0].ContentType.Split('/');
        //var _suffix = suffix[1];
        //var _temp = System.Web.HttpContext.Current.Request["name"];

        //if (!string.IsNullOrEmpty(_temp))
        //{
        //    name = _temp;
        //}
        //else
        //{
        Random rand = new Random(24 * (int)DateTime.Now.Ticks);
        var ranNumber = rand.Next();
        name = ranNumber + ".jpg";
        //}

        if (!string.IsNullOrEmpty(HttpContext.Current.Request["_name"]) && HttpContext.Current.Request["_name"] != "null")
            ranNumber = int.Parse(HttpContext.Current.Request["_name"]);

        string makeThumb = "";
        var _base64 = System.Web.HttpContext.Current.Request["_base64"];
        if (!string.IsNullOrEmpty(_base64))
        {
            makeThumb = Base64StrToImage(_base64, serverPath, ranNumber.ToString());
        }
        else
        {
            var full = serverPath + name;
            files[0].SaveAs(full);
        }
        var _result = "{\"jsonrpc\" : \"2.0\", \"result\" : \"" + ranNumber + "\", \"id\" : \"" + basePath + name + "\"}";
        System.Web.HttpContext.Current.Response.Write(_result);
    }

    /// <summary>
    /// 将Base64字符串转换为图片并保存到本地
    /// </summary>
    /// <param name="base64Str">base64字符串</param>
    /// <param name="savePath">图片保存地址，如：/dis/Images/10000.png</param>
    /// <returns></returns>
    public static string Base64StrToImage(string base64Str, string serverPath, string name)
    {
        var ret = "";
        try
        {
            serverPath = serverPath.Replace("upload", "Up");

            if (!Directory.Exists(serverPath))
                Directory.CreateDirectory(serverPath);

            var base64 = base64Str;//System.Web.HttpContext.Current.Request["_base64"];
            base64 = base64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
            byte[] bytes = Convert.FromBase64String(base64);
            MemoryStream memStream = new MemoryStream(bytes);
            Image mImage = Image.FromStream(memStream);

            Bitmap bp = new Bitmap(mImage);
            MemoryStream ms = new MemoryStream();

            bp.Save(serverPath + name + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            ms.Close();
            bp.Dispose();
            ret = serverPath + name + ".jpg";
        }
        catch (Exception ex)
        {
            ret = "";
        }
        return ret;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}